package resman.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import resman.bean.ResumeBean;
import resman.bean.TextBean;
import resman.database.DatabaseHandler;
import resman.database.TransSession;
import resman.model.ActionServlet;

@SuppressWarnings("serial")
@WebServlet("/TextServlet")
public class TextServlet extends ActionServlet
{
	
	@Override
	protected void process(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();
		
		ResumeBean resume = getResume(request);

		int op = getOpParameter("op",  request);
		int id = getIntParameter("tid", request);
		
		TextBean text;
		
		if (id != -1)
			text = resume.getText(id);
		else
			text = new TextBean();
		
		if (op == ADD_OP)
		{
			text.setProperties(request.getParameterMap());
			
			if (id == -1)
			{
				text.setResume(resume);
				resume.getTexts().add(text);
				session.save(text);
			}
			else
				session.merge(text);
		}
		else
		{
			resume.getTexts().remove(text);
			session.delete(text);
		}
		
		tsession.close();
		dispatchTo("views/text_view.jsp", request, response);
	}

}
